import useAppContext from "@/hooks/useAppContext";
import { useRouter } from "@tarojs/taro"
import { useRequest } from "ahooks"
import { useState } from "react";
import { fetchArchery, fetchContact, fetchCustomerInfo, fetchIsStar, fetchStarUser, fetchUnStarUser } from "./service"
import { IStarOptions } from "./types";

function useData() {
  const [starFlag, setStarFlag] = useState<boolean>(false);
  const { params } = useRouter<{ id: string }>()
  const userInfo = useAppContext(state => state.userInfo)
  const { data: customerInfo, refresh } = useRequest(() => fetchCustomerInfo({ customerId: params.id }), {
    formatResult: (e) => e.res
  })
  const { data: isPermissionContact = false } = useRequest(() => fetchContact({ customerId: params.id }), {
    formatResult: (e) => e.res
  })
  const { data: isStar } = useRequest(() => fetchIsStar(params.id), {
    formatResult: (e) => e.res
  })
  const { run: onStarUser } = useRequest((options: IStarOptions) => fetchStarUser(options), {
    manual: true,
    formatResult: (e) => e.res,
    onSuccess() {
      refresh()
    }
  })
  const { run: onUnStarUser } = useRequest((id: string) => fetchUnStarUser(id), {
    manual: true,
    formatResult: (e) => e.res,
    onSuccess() {
      refresh()
    }
  })

  /** 射箭 */
  const { run: executeArchery } = useRequest(() => fetchArchery({ customerId: customerInfo!.id }), {
    manual: true,
  })

  /** 收藏/取消收藏 */
  const onStar = () => {
    onStarUser({ collectCustomerId: params.id })
  }

  /** 点击联系 */
  const onConnect = () => {

  }

  const onArchery = () => {
    if (userInfo.vip === '0') {
      return Taro.showModal({
        title: '你还不是VIP用户哦~',
        showCancel: false,
        confirmColor: '#e7495d'
      })
    }
    executeArchery()
  }

  return {
    starFlag,
    customerInfo: customerInfo,
    userInfo,
    isPermissionContact,
    isStar,
    onStar,
    onArchery,
    setStarFlag,
    onStarUser,
    onUnStarUser,
    onConnect
  }
}

export default useData